package com.thinkgem.dingdan.common.file;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.thinkgem.dingdan.modules.bu.entity.BuOrder;
import com.thinkgem.dingdan.modules.bu.service.IBuOrderService;

@Controller
@RequestMapping(value = "sync")
public class SyncFileController {

	@Autowired
	private IBuOrderService buOrderService;
	
	@Value("${accessKey}")
	private String accessKey;
	@Value("${secretKey}")
	private String secretKey;
	@Value("${orderBucket}")
	private String bucket;
	@Value("${picPreffixUrl}")
	private String preffix;
	@Value("${httpPriffix}")
	private String httpPriffix;
	
	@RequestMapping(value = "file",method = RequestMethod.GET)
	public void syncFile(HttpServletRequest request,HttpServletResponse response){
		
		try{
			List<BuOrder> orderList = buOrderService.findImageList();
			for(int i = 0;i<orderList.size();i++){
				String picUrl = orderList.get(i).getPicUrl();
				byte[] uploadBytes = checkUrl(httpPriffix+picUrl);
				String fileName = new Date().getTime() + picUrl.substring(picUrl.lastIndexOf("."));
				if(uploadBytes.length>0){
					SevenCattleUploadUtil.result(accessKey, secretKey, bucket, uploadBytes, fileName);
					buOrderService.updateImageUrl(orderList.get(i).getId(), fileName);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	private static byte[] checkUrl(String picUrl)throws Exception{
		URL url = new URL(picUrl);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setConnectTimeout(5000);
		InputStream in = null;
		if(conn.getResponseCode() == 200){
			in = conn.getInputStream();
		}
		byte[] uploadBytes = toByteArray(in);
		in.close();
		return uploadBytes;
	}
	
	public static byte[] toByteArray(InputStream input) throws IOException {
	    ByteArrayOutputStream output = new ByteArrayOutputStream();
	    byte[] buffer = new byte[4096];
	    int n = 0;
	    while (-1 != (n = input.read(buffer))) {
	        output.write(buffer, 0, n);
	    }
	    return output.toByteArray();
	}
	
}
